package project.userAED;

import javax.servlet.*;
import javax.servlet.http.*;

import org.json.JSONException;
import org.json.JSONObject;
import project.Dao.UserDao;
import project.Domain.User;

import java.io.IOException;

public class userAED extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行了doGet");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行了doPost");
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("执行了service");
        try {
            processAEdFile(request, response);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    protected void processAEdFile(HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException {


        request.setCharacterEncoding("UTF-8");
//        获取操作方式增删改
        String oper = request.getParameter("oper");
        String id = request.getParameter("id");
        String name = request.getParameter("user_name");
        String email = request.getParameter("user_email");
        String mobile = request.getParameter("user_mobile");
        String role = request.getParameter("user_role");
        String leaderID = request.getParameter("leaderID");
//        创建userDao对象操作数据库
        UserDao UserDao = new UserDao();
//        创建JSON对象封装返回信息
        JSONObject json = new JSONObject();
        switch (oper){
            case "del":
                if(UserDao.delete(Integer.parseInt(id))){
                    json.put("result_msg", "ok");
                }else{
                    json.put("result_msg", "error");
                }
                break;
            case "edit":
//                利用传过来的信息封装user对象
                User userEdit = new User(Integer.parseInt(id), name, email, mobile, role, null, null);
                UserDao.edit(userEdit);
                break;
            case "add":
                User userAdd = new User(-1, name, email, mobile, role, null, null,Integer.parseInt(leaderID));
                UserDao.add(userAdd);
                break;
        }

    }
}

